/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.sgf.compile;

import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationService;
import com.inspur.edp.sgf.api.entity.ServiceOperation;
import com.inspur.edp.sgf.api.entity.ServiceParameter;
import com.inspur.edp.sgf.api.entity.SgMetadata;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Objects;

/**
 * 功能描述: @ClassName: EapiRtHandler @Author: Fynn Qi @Date: 2020/9/17 18:40 @Version: V1.0
 */
public class EapiRtHandler {

    private static final String[] WHITE_VO_OPERATION_NAME_LIST = new String[]{"CloseSession", "DeleteAndSave", "RetrieveWithChildPagination", "QueryChild"};

    private static final String REQUEST_INFO = "RequestInfo";

    public static SgMetadata handler(SgMetadata metadata) {

        String resourceType = metadata.getService().getResourceType();
        String resourceId = metadata.getService().getResourceId();
        switch (resourceType) {
            case ResourceType.EAPI_RESOURCE_TYPE_VO:
                //修改日期：2021-7-6
                //修改说明：将视图对象资源ID修改为元数据ID，不再使用ConfigId
                //resourceIdHandler(metadata, resourceId);
                paramHandler(metadata);
                break;
            case ResourceType.EAPI_RESOURCE_TYPE_VO_SIMPLE:
                //修改日期：2021-7-6
                //修改说明：将视图对象资源ID修改为元数据ID，不再使用ConfigId
                //resourceIdHandler(metadata, resourceId);
                break;
            default:
                break;
        }
        return metadata;
    }

    private static void resourceIdHandler(SgMetadata metadata, String resourceId) {
        metadata.getService().setResourceId(getViewModelConfigId(resourceId));
    }

    private static void paramHandler(SgMetadata metadata) {
        if (metadata.getService().getOperations() == null
                || metadata.getService().getOperations().size() <= 0) {
            return;
        }
        for (ServiceOperation operation : metadata.getService().getOperations()) {
            if (operation.getParameters() == null || operation.getParameters().size() <= 0) {
                return;
            }
            //兼容处理requestInfo
            for (ServiceParameter parameter : operation.getParameters()) {
                if (REQUEST_INFO.equals(parameter.getCode())) {
                    parameter.setCode("requestInfo");
                }
            }
        }
    }

    public static boolean isInWhiteList(String operationName) {
        if (StringUtils.isBlank(operationName)) {
            return false;
        }
        return Arrays.asList(WHITE_VO_OPERATION_NAME_LIST).contains(operationName);
    }

    private static String getViewModelConfigId(String metadataId) {
        GspViewModel viewModel = getGspViewModel(metadataId);
        return viewModel.getGeneratedConfigID();
    }

    public static GspViewModel getGspViewModel(String metadataId) {
        // 获取运行时运行环境中的元数据
        GspMetadata voMetadata = getCustomizationMetadata(metadataId);
        if (Objects.isNull(voMetadata)) {
            throw new RuntimeException(MessageFormat.format("获取运行时VO元数据{0}失败！", metadataId));
        }
        IMetadataContent content = voMetadata.getContent();
        if (Objects.isNull(content)) {
            throw new RuntimeException(MessageFormat.format("运行时VO元数据{0}的Content为空！", metadataId));
        }
        try {
            return (GspViewModel) content;
        } catch (Exception e) {
            throw new RuntimeException(
                    MessageFormat.format("运行时VO元数据(ID:{0})Content转换为GspViewModel失败！", metadataId), e);
        }
    }

    public static GspMetadata getCustomizationMetadata(String metadataId) {
        CustomizationService service = SpringBeanUtils.getBean(CustomizationService.class);
        GspMetadata metadata = service.getMetadata(metadataId);
        return metadata;
    }
}
